package net.vicp.fyhui.tool.smalltool.config;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

/**
 * 读取配置文件，获取属性值
 */
public class PropertiesUtil {

    private final static Logger logger = LogManager.getLogger();

    static Properties properties;

    /**
     *
     * @param propertiesPath 默认为jar同级目录下config目录中的文件
     */
    static {
        if(properties == null){
            properties = new Properties();
        }
    }
    public static void loadProperties(String propertiesPath){
        File file = new File(propertiesPath);
        try {
            properties.load(new FileReader(file));
            System.out.println("配置文件加载成功^_^");
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(String.format("配置文件加载错误：[%s]",file.getAbsolutePath()));
        }
    }

    public static void loadAllProperties(String propertiesDirPath){
        File file = new File(propertiesDirPath);
        if(file == null){
            logger.error(String.format("配置文件加载错误：[%s]",file.getAbsolutePath()));
        }
        File[] files = file.listFiles();
        for(File file1:files){
            try {
                properties.load(new FileReader(file1));
                System.out.println(String.format("配置文件加载成功^_^,[%s]",file1.getAbsolutePath()));
            } catch (IOException e) {
                e.printStackTrace();
                logger.error(String.format("配置文件加载错误：[%s]",file1.getAbsolutePath()));
            }
        }
    }
    public static String getProperties(String propertiesKey){
        return properties.getProperty(propertiesKey);
    }
    public static String getProperties(String propertitesPath,String key){
        loadProperties(propertitesPath);
        return getProperties(key);
    }


    public static void main(String[] args) throws FileNotFoundException {
        File file = new File("config/datahandler.properties");
//        String filepath = "config/datahandler.properties";
        String filepath = "config";
        PropertiesUtil.loadAllProperties(filepath);

        for(Object key:properties.keySet()){
            System.out.println(String.format("[%s]\t[%s]",key,properties.get(key)));
        }

        System.err.println(PropertiesUtil.getProperties("type-1"));
        System.err.println(PropertiesUtil.getProperties("config/datahandler.properties","type-1"));

    }
}
